import java.io.Serializable;
import java.util.ArrayList;

public class Map implements Serializable {
  private int rows, cols;
  private Territory[][] board;
  
  public Map(int numRows, int numCols) {
    board = new Territory[numRows][numCols];
    rows = numRows; cols = numCols;
    initMap();
  }
  
  public Map(Territory[][] board) {
    this.board = board;
    rows = board.length; cols = board[0].length;
  }
  
  public Map() {
	 this(10,10);
  }
  
  public void initMap() {
	  for(int i = 0; i < rows; i++) {
		  for(int j = 0; j < cols; j++) {
			  board[i][j] = new Territory(i,j);
		  }
	  }
  }
  
  public int getRows() {
	  return rows;
  }
  
  public int getCols() {
	  return cols;
  }
  
  public void updateTerritory(int row, int col, Territory terr) {
    if(row < 0 || row > board.length) return;
    if(col < 0 || row > board[0].length) return;
    board[row][col] = terr;
  }
  
  public Territory getTerritory (int row, int col) {
    //if(row < 0 || row > board.length) return null;
    //if(col < 0 || col > board[0].length) return null;
    return (row < 0 || row >= board.length || col < 0 || col >= board[0].length) ? null : board[row][col];
  }
  
  public boolean FindPath(Territory s, Territory d) {
	  String owner = s.getOwner();
	  if(!owner.equals(d.getOwner())) {
		  return (Math.abs(s.gety() - d.gety()) < 2 && Math.abs(s.gety() - d.gety()) < 2);
	  } else
		  return (routeProcess(s.getx()+1,s.gety(),d) || routeProcess(s.getx()-1,s.gety(),d) 
				  || routeProcess(s.getx(),s.gety()+1,d) || routeProcess(s.getx(),s.gety()-1,d));
	  //Needs to be re-implemented (its kinda sloppy)
  }
  
  private boolean routeProcess(int x, int y, Territory d) {
	if(x < 0 || y < 0 || x >= rows || y >= cols)
		return false;
	if(board[x][y].getOwner() != d.getOwner())
		return false;
	if(x == d.gety() && y == d.gety())
		return true;
	return false;
  }
  
  public void SetupMap(ArrayList<Territory> updates) {
	  for(Territory t : updates) {
		  board[t.gety()][t.gety()].AddAmount(t.getTroopAmount());
		  board[t.gety()][t.gety()].setOwner(t.getOwner());
		  board[t.gety()][t.gety()].SetUpdated(false);
	  }
  }
  
  public ArrayList<Territory> updatedList() {
	 ArrayList<Territory> updates = new ArrayList<Territory>();
	 for(Territory[] row : board) { 
		 for(Territory t : row) {
			if(t.CheckUpdated())
				updates.add(t);
		 }
	 }
	 return updates; 
  }
  
  public void printMap() {
	  for(int i = 0; i < rows; i++) {
		  for(int j = 0; j < cols; j++) {
			  System.out.println("Territory: " + i + "," + j + " - owner: " + getTerritory(i,j).getOwner());
		  }
	  }
  }
  
}